import { defineComponent, reactive, ref, unref } from 'vue';
import './index.less';
import type { DeckList, DeckItem } from '/@/api/gateruler/model/deckModel';
import { useUserStore } from '/@/store/modules/user';
import Title from '/@/views/gateruler/components/Title';
import { Button, ConfigProvider, Checkbox } from 'vant';
import { DeckListApi, DeleteDeckApi } from '/@/api/gateruler/deck';
import { awaitWrap, aTabClick } from '/@/utils';
import { formatToDateTime } from '/@/utils/dateUtil';
import { find, remove } from 'lodash-es';
import { useMessage } from '/@/hooks/web/useMessage';
import { useGo } from '/@/hooks/web/usePage';
import { appShareUsing, getAppParameters } from '/@/utils/appInteractive';
import { useGateRulerStore } from '/@/store/modules/gateruler';
import { useOptions } from '/@/views/gateruler/hooks/useOptions';

export default defineComponent({
  name: 'GateRulerDeckPage',
  setup() {
    // 设置分享参数
    getAppParameters(); // 需要重新获取一下token 因为是在app使用
    appShareUsing({} as any);

    const go = useGo();
    const userStore = useUserStore();
    const gaterulerStore = useGateRulerStore();
    const { createSuccessToast } = useMessage();
    const { legionOptions } = useOptions();

    const switchState = ref(false); // 是否出现删除按钮
    const selectedAll = ref(false); // 是否全选
    const selectedDeckIds = ref<number[]>([]);
    const SwitchButton = () => {
      if (!userStore.getToken) {
        return null;
      }
      const themeVars = {
        buttonBorderWidth: 0,
        buttonDefaultBackground: 'none',
      };
      if (unref(switchState)) {
        return (
          <ConfigProvider
            themeVars={{
              ...themeVars,
              buttonDefaultColor: '#1380F0',
            }}
          >
            <Button
              size={'small'}
              icon={'success'}
              onClick={() => {
                switchState.value = false;
              }}
            >
              完成
            </Button>
          </ConfigProvider>
        );
      }
      return (
        <ConfigProvider themeVars={themeVars}>
          <Button
            size={'small'}
            icon={'bars'}
            iconPosition={'right'}
            onClick={() => {
              switchState.value = true;
              selectedAll.value = false;
              deckList.rows.map((item) => {
                item.isCheck = false;
              });
              selectedDeckIds.value = [];
            }}
          >
            编辑
          </Button>
        </ConfigProvider>
      );
    };
    const BottomBox = () => {
      const selectAllClick = (val: boolean) => {
        deckList.rows.map((item) => {
          item.isCheck = val;
        });
      };
      const token = userStore.getToken;
      let actionHtml: VueNode = null;
      const themeVars = {
        buttonBorderWidth: 0,
        buttonDefaultBackground: 'none',
        buttonDefaultColor: '#1380F0',
      };
      if (!token) {
        aTabClick('wanxiu://innerlink?type=weblogin');
      }
      actionHtml = (
        <a class={'block'}>
          <ConfigProvider themeVars={themeVars}>
            <Button
              icon={'plus'}
              size={'large'}
              onClick={() => {
                if (!token) {
                  aTabClick('wanxiu://innerlink?type=weblogin');
                  return false;
                }
                gaterulerStore.clearCreateDeckParams();
                go('/gaterulecreate', true);
              }}
            >
              创建套牌
            </Button>
          </ConfigProvider>
        </a>
      );
      if (unref(switchState)) {
        actionHtml = (
          <ConfigProvider
            themeVars={{
              checkboxLabelColor: '#1380F0',
            }}
            class={'delete-box flex items-center h-full justify-between'}
          >
            <Checkbox v-model={[selectedAll.value]} onChange={selectAllClick}>
              全选
            </Checkbox>
            <Button size={'small'} type={'primary'} disabled={!unref(selectedDeckIds).length} onClick={deleteDeck}>
              删除
            </Button>
          </ConfigProvider>
        );
      }
      return <div class={'bottom-action-box'}>{actionHtml}</div>;
    };
    const DeckListBox = () => {
      const listItemHtml: VueNode[] = [];
      const deckItemChange = (val: boolean, deck: DeckItem) => {
        if (val) {
          unref(selectedDeckIds).push(deck.id);
        } else {
          const index = unref(selectedDeckIds).indexOf(deck.id);
          unref(selectedDeckIds).splice(index, 1);
        }
      };
      for (let i = 0; i < deckList.rows.length; i++) {
        const item = deckList.rows[i];
        listItemHtml.push(
          <li class={unref(switchState) ? 'deck-list-item selected' : 'deck-list-item'}>
            {unref(switchState) ? (
              <div class={'checks'}>
                <Checkbox
                  v-model={[item.isCheck]}
                  onChange={(val) => {
                    deckItemChange(val, item);
                  }}
                />
              </div>
            ) : null}
            <div
              onClick={() => {
                go(`/gaterulerdeck/${item.id}`);
              }}
            >
              <div class={'item-title flex justify-between'}>
                <span>{item.deck_name}</span>
                <span class={'text-gray-400'}>{formatToDateTime(item.created_at, 'YYYY-MM-DD')}</span>
              </div>
              <div class={'images flex'}>
                {item.legion.map((img) => {
                  const imageName = find(legionOptions, ['value', img]);
                  return (
                    <div class={'image'}>
                      <img
                        src={`https://pic.iyingdi.com/card-tools/yingdiimg/gateruler/card/${imageName?.label}.png`}
                        alt=''
                      />
                    </div>
                  );
                })}
              </div>
              <div class={'main-nums absolute'}>{item.cards_number}张</div>
            </div>
          </li>
        );
      }
      return <ul class={'deck-list-box'}>{listItemHtml}</ul>;
    };

    const deckList = reactive<DeckList>({
      total: 0,
      rows: [],
    });
    const getList = async () => {
      const [error, data] = await awaitWrap(DeckListApi({ page: 1, page_size: 120 }));
      if (error) {
        return;
      }
      const result = data as DeckList;
      deckList.total = result.total;
      deckList.rows = result.rows;
    };
    getList();
    const deleteDeck = async () => {
      const [error] = await awaitWrap(DeleteDeckApi(unref(selectedDeckIds)));
      if (error) {
        return false;
      }
      remove(deckList.rows, (item) => {
        return unref(selectedDeckIds).indexOf(item.id) >= 0;
      });
      selectedDeckIds.value = [];
      createSuccessToast({
        message: '套牌删除成功',
      });
    };

    return () => (
      <div class={'gateruler-deck-page'}>
        <Title title='门将GateRuler我的套牌' />
        <div class={'deck-list-container'}>
          <div class={'switch-box flex justify-between text-sm'}>
            <span>我的套牌</span>
            <SwitchButton />
          </div>
          <BottomBox />
          <DeckListBox />
        </div>
      </div>
    );
  },
});
